package com.qdsg.ysg.doctor.ui.activity.prescription;

import android.annotation.SuppressLint;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Canvas;
import android.graphics.Rect;
import android.text.TextUtils;
import android.util.Base64;
import android.view.View;
import android.widget.ImageView;
import android.widget.TextView;

import androidx.constraintlayout.widget.ConstraintLayout;
import androidx.core.content.ContextCompat;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.qdsg.ysg.doctor.R;
import com.qdsg.ysg.doctor.base.BaseActivity;
import com.qdsg.ysg.doctor.ui.adapter.MedicineDetailAdapter;
import com.qdsg.ysg.doctor.util.DpUtil;
import com.qdsg.ysg.doctor.util.ImageLoaderHelper;
import com.qdsg.ysg.doctor.util.ToastUtil;
import com.rest.business.RestProxy;
import com.rest.response.BaseResponse;
import com.rest.response.PrescriptionDetailResponse;

import org.jetbrains.annotations.NotNull;

import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import io.reactivex.Observer;
import io.reactivex.disposables.Disposable;

/**
 * 处方详情
 * Created by lbj on 2022/1/6 14:53
 * @author DELL
 */

public class AtyOrderMedicineDetailActivity extends BaseActivity {
    @BindView(R.id.tv_title)
    TextView tvTitle;
    @BindView(R.id.tv_chufang_number)
    TextView tvChufangNumber;
    @BindView(R.id.tv_patient_name)
    TextView tvPatientName;
    @BindView(R.id.tv_patient_sex)
    TextView tvPatientSex;
    @BindView(R.id.tv_patient_age)
    TextView tvPatientAge;
    @BindView(R.id.tv_patient_no)
    TextView tvPatientNo;
    @BindView(R.id.tv_diagnose)
    TextView tvDiagnose;
    @BindView(R.id.tv_time_kaifeng)
    TextView tvTimeKaifeng;
    @BindView(R.id.rv_medicine)
    RecyclerView rvMedicine;
    @BindView(R.id.tv_all_price)
    TextView tvAllPrice;
    @BindView(R.id.tv_compound_doctor_name)
    TextView tvCompoundDoctorName;
    @BindView(R.id.tv_distribute_doctor_name)
    TextView tvDistributeDoctorName;
    @BindView(R.id.tv_status)
    TextView tvStatus;
    @BindView(R.id.tv_style_name)
    TextView tvStyleName;
    @BindView(R.id.tv_receive_name)
    TextView tvReceiveName;
    @BindView(R.id.tv_number)
    TextView tvNumber;
    @BindView(R.id.tv_create_time)
    TextView tvCreateTime;
    @BindView(R.id.tv_pay_time)
    TextView tvPayTime;
    @BindView(R.id.cl_address)
    ConstraintLayout clAddress;
    @BindView(R.id.iv_auditorSignImg)
    ImageView ivAuditorSignImg;
    @BindView(R.id.iv_openDoctorSignImg)
    ImageView ivOpenDoctorSignImg;
    @BindView(R.id.tv_doctor_name)
    TextView tvDoctorName;
    @BindView(R.id.iv_auditorSignImg_date)
    TextView ivAuditorSignImgDate;
    @BindView(R.id.tv_department)
    TextView tvDepartment;
    @BindView(R.id.identity_num)
    TextView identityNum;
    @BindView(R.id.img_head)
    ImageView imghead;
    @BindView(R.id.tv_diagnose_advice)
    TextView tvDiagnoseAdvice;
    @BindView(R.id.tv_advice)
    TextView tvAdvice;
    @BindView(R.id.iv_openDoctorSign_date)
    TextView ivOpenDoctorSignDate;

    @BindView(R.id.tv_check)
    TextView tv_check;
    @BindView(R.id.btn_confirm)
    TextView btn_confirm;

    private String hospitalPhone, orderId, receiverAddress, receiverPhone, prescriptionId;
    List<PrescriptionDetailResponse.Prescription> list = new ArrayList<>();
    MedicineDetailAdapter adapter;

    @Override
    protected int getLayoutResource() {
        return R.layout.aty_medicine_detail;
    }

    @SuppressLint("SetTextI18n")
    @Override
    protected void initViews() {
        tvTitle.setText("处方详情");
        LinearLayoutManager manager = new LinearLayoutManager(this);
        manager.setOrientation(LinearLayoutManager.VERTICAL);
        rvMedicine.setLayoutManager(manager);
        adapter = new MedicineDetailAdapter(this, list);
        rvMedicine.setAdapter(adapter);
        rvMedicine.addItemDecoration(new RecyclerView.ItemDecoration() {
            @Override
            public void onDraw(@NotNull Canvas c, @NotNull RecyclerView parent, @NotNull RecyclerView.State state) {
                super.onDraw(c, parent, state);
            }

            @Override
            public void getItemOffsets(@NotNull Rect outRect, @NotNull View view, @NotNull RecyclerView parent, @NotNull RecyclerView.State state) {
                super.getItemOffsets(outRect, view, parent, state);
                outRect.bottom = DpUtil.dip2px(mContext, 1);
            }
        });
        btn_confirm.setOnClickListener(v -> {
            backPrescription(prescriptionId, "1");
        });
    }

    @Override
    protected void initData() {
        orderId = getIntent().getStringExtra("orderId");
        getMedicineOrderDetail(orderId);
    }


    private void getMedicineOrderDetail(String orderId) {
        showProgressDialog(mContext);
        RestProxy.getInstance().getMedicineOrderDetail(orderId, new Observer<PrescriptionDetailResponse>() {
            @Override
            public void onSubscribe(Disposable d) {

            }

            @SuppressLint("SetTextI18n")
            @Override
            public void onNext(PrescriptionDetailResponse prescriptionResponse) {
                dismissProgressDialog();
                PrescriptionDetailResponse.PrescriptionWrapper data = prescriptionResponse.data;
                if ("3".equals(prescriptionResponse.data.receiveType)) {//医院自取
                    tvStyleName.setText("院内自取");
                    tvReceiveName.setText(data.hospitalName);
                } else if ("0".equals(prescriptionResponse.data.receiveType)) {//未审核
                    tvStyleName.setText("");
                    tvReceiveName.setText("");
                } else {
                    tvStyleName.setText("物流配送");
                    tvReceiveName.setText(data.receiverName + "," + data.receiverPhone + "," + data.receiverAddress);
                }
                prescriptionId = prescriptionResponse.data.preId;
//                ImageLoaderHelper.getInstance().GlideImageLoader(mContext,prescriptionResponse.data.,imghead);
                tvDoctorName.setText(prescriptionResponse.data.doctorName);
                ivAuditorSignImgDate.setText(prescriptionResponse.data.passTime);
                tvDepartment.setText(prescriptionResponse.data.openDoctorDept);
                identityNum.setText("身份证：" + prescriptionResponse.data.patientIdcard);
                tvDiagnoseAdvice.setText("用药嘱托：" + prescriptionResponse.data.remark);
                tvAdvice.setText("医生建议：" + prescriptionResponse.data.diagnoseAdvice);

                ImageLoaderHelper.getInstance().GlideImageLoader(mContext,prescriptionResponse.data.openDoctorSignImg,ivOpenDoctorSignImg);
//                byte[] decodedString = Base64.decode(prescriptionResponse.data.openDoctorSignImg, Base64.DEFAULT);
//                Bitmap decodedByte = BitmapFactory.decodeByteArray(decodedString, 0, decodedString.length);
//                ivOpenDoctorSignImg.setImageBitmap(decodedByte);

//                byte[] decodedString1 = Base64.decode(prescriptionResponse.data.auditorSignImg, Base64.DEFAULT);
//                Bitmap bitmap = BitmapFactory.decodeByteArray(decodedString1, 0, decodedString1.length);
//                ivAuditorSignImg.setImageBitmap(bitmap);

                tvCompoundDoctorName.setText("调配：" + (TextUtils.isEmpty(prescriptionResponse.data.compoundDoctorName)?"":prescriptionResponse.data.compoundDoctorName) +" "+ ((TextUtils.isEmpty(prescriptionResponse.data.compoundTime)?"":prescriptionResponse.data.compoundTime)));
                tvDistributeDoctorName.setText("发药：" + (TextUtils.isEmpty(prescriptionResponse.data.distributeDoctorName)?"":prescriptionResponse.data.distributeDoctorName)+" "+(TextUtils.isEmpty(prescriptionResponse.data.distributeTime)?"":prescriptionResponse.data.distributeTime));
                tvTimeKaifeng.setText("开方日期：" + prescriptionResponse.data.preTime);
                tvAllPrice.setText(prescriptionResponse.data.prescriptionAmount);
                hospitalPhone = prescriptionResponse.data.hospitalPhone;
                tvPatientNo.setText("门诊病历号: " + prescriptionResponse.data.medicalId);
                setStatusColor(tvStatus, data.status);
                tvStatus.setText(data.statusName);
                tvPatientName.setText("患者：" + data.patientName);
                tvPatientSex.setText("性别："+data.patientSex);
                tvPatientAge.setText("年龄: "+data.patientAge + "岁");
                tvDiagnose.setText("诊断: " + prescriptionResponse.data.preAppend + " " + prescriptionResponse.data.icd + " " + prescriptionResponse.data.tailAppend);
                tvNumber.setText(data.orderId);
                tvCreateTime.setText(data.createTime);
                ivOpenDoctorSignDate.setText(data.createTime);

                tvPayTime.setText(data.payTime);
                String status = prescriptionResponse.data.status;
                if (status.equals("0") || status.equals("1")) {
                    btn_confirm.setVisibility(View.VISIBLE);
                } else {
                    btn_confirm.setVisibility(View.GONE);
                }
                if (status.equals("0")) {//待审核，可撤销
                    tv_check.setText("待审核");
                } else if (status.equals("1")) {
                    tv_check.setText("审核通过，待确认");
                } else if (status.equals("2")) {
                    tv_check.setText("审核驳回");
                } else if (status.equals("3")) {
                    tv_check.setText("患者已确认(不可撤销)");
                } else if (status.equals("7")) {
                    tv_check.setText("已取消");
                } else {
                    tv_check.setText(prescriptionResponse.data.statusName);
                }

                list.clear();
                list.addAll(prescriptionResponse.data.westernNameDtoList);
                adapter.notifyDataSetChanged();

            }

            @Override
            public void onError(Throwable e) {
                dismissProgressDialog();
                ToastUtil.onError(mContext, e);
            }

            @Override
            public void onComplete() {

            }
        });
    }


    private void setStatusColor(TextView tvStatus, String status) {
        switch (status) {
            case "5":
            case "7":
            case "11":
                tvStatus.setTextColor(ContextCompat.getColor(mContext, R.color.ff999999));
                break;

            default:
                tvStatus.setTextColor(ContextCompat.getColor(mContext, R.color.fff54c4c));
        }
    }


    private String getStatus(int status) {
        switch (status) {
            case 401:
                return "待支付";
            case 402:
                return "未发货";
            case 403:
                return "已发货";
            case 404:
                return "已收货";
            case 405:
                return "待领取";
            default:
                return "";
        }
    }

    private void backPrescription(String id, String type) {
        RestProxy.getInstance().backPrescription(id, type, new Observer<BaseResponse>() {
            @Override
            public void onSubscribe(Disposable d) {
            }

            @Override
            public void onNext(BaseResponse baseResponse) {
                setResult(RESULT_OK);
                finish();
            }

            @Override
            public void onError(Throwable e) {
                ToastUtil.onError(mContext, e);
            }

            @Override
            public void onComplete() {
            }
        });
    }
}
